from models import db
from models.sessions import Sessions, Conversations, EventType, ReviewType
import uuid
from datetime import datetime
from typing import List, Dict

class ConversationService:
    def create_session(self, user_id: int, query: str, event_type) -> str:
        """创建新的会话"""
        session_id = str(uuid.uuid4())
        session = Sessions(
            session_id=session_id,
            user_id=user_id,
            event_type=event_type,
            initial_query=query,
            is_active=True,
            start_time=datetime.utcnow()
        )
        db.session.add(session)
        db.session.commit()
        return session_id

    def end_session(self, session_id: str):
        """结束会话"""
        session = Sessions.query.get(session_id)
        if session:
            session.is_active = False
            session.end_time = datetime.utcnow()
            db.session.commit()

    def add_conversation(self, session_id: str, user_query: str, response: str, key_info: str = None) -> str:
        """添加对话记录"""
        conversation_id = str(uuid.uuid4())
        conversation = Conversations(
            conversation_id=conversation_id,
            session_id=session_id,
            user_query=user_query,
            response=response,
            key_info=key_info,
            create_time=datetime.utcnow()
        )
        db.session.add(conversation)
        db.session.commit()
        return conversation_id

    def get_conversation_history(self, session_id: str, limit: int = 5) -> List[Dict]:
        """获取会话历史记录"""
        conversation_history = []
        records = Conversations.query.filter_by(session_id=session_id).order_by(Conversations.create_time.desc()).limit(limit).all()
        for row in reversed(records):
            if row.user_query:
                conversation_history.append({"role": "user", "content": row.user_query})
            if row.key_info:
                conversation_history.append({"role": "assistant", "content": row.key_info})
        return conversation_history
        
    def update_conversation(self, conversation_id: str, response: str, key_info: str) -> bool:
        """
        更新对话记录
        
        Args:
            conversation_id (str): 对话ID
            response (str): 完整的响应内容
            key_info (str): 关键信息（SQL或查询参数）
            
        Returns:
            bool: 更新是否成功
        """
        try:
            conversation = Conversations.query.get(conversation_id)
            if conversation:
                conversation.response = response
                conversation.key_info = key_info
                db.session.commit()
                return True
            return False
        except Exception as e:
            print(f"更新对话记录失败: {str(e)}")
            db.session.rollback()
            return False


    def update_conversation_review(self, conversation_id: str, review: str):
        """更新对话反馈"""
        conversation = Conversations.query.get(conversation_id)
        if conversation:
            if review in [r.value for r in ReviewType]:
                conversation.review = ReviewType(review)
                db.session.commit()

    def close(self):
        """兼容旧接口，无需实现"""
        pass
class SessionService:
    def update_session(self, session_id: str, initial_query: str, event_type=None) -> bool:
        """
        更新会话记录，设置 initial_query、结束时间和活跃状态以及 event_type。

        Args:
            session_id (str): 会话 ID
            initial_query (str): 初始查询内容

        Returns:
            bool: 是否更新成功
        """
        try:
            session = Sessions.query.get(session_id)
            if session:
                session.initial_query = initial_query
                if event_type is not None:
                    session.event_type = event_type
                session.end_time = datetime.now()
                session.is_active = 0
                db.session.commit()
                return True
            return False
        except Exception as e:
            print(f"更新会话记录失败: {str(e)}")
            if session:
                try:
                    session.end_time = datetime.now()
                    session.is_active = 0
                    db.session.commit()
                except Exception as rollback_error:
                    print(f"异常后更新结束时间失败: {rollback_error}")
                    db.session.rollback()
            return False